import { Component, OnInit } from '@angular/core';
import { FadeInTop } from "../../../shared/animations/fade-in-top.decorator";
import { JsonApiService } from "app/core/api/json-api.service";
import { NotificationService } from "../../../shared/utils/notification.service";
import { config } from '../../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入


declare var $: any;
declare var BMap: any;
declare var echarts: any;
declare var toMapPoint: any;
@Component({
	selector: 'sa-order-gps',
	templateUrl: './order-gps.component.html',
	styleUrls: ['./order-gps.css']
})
export class OrderGPSComponent implements OnInit {
	constructor(private jsonApiService: JsonApiService, private notificationService: NotificationService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {});
	}
	tableData:any[] = []; //table数据
	totalCounts:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	startTime:string = '';//过滤条件:开始时间
	endTime:string = '';//过滤条件:结束时间
	searchKey:string = ''; //过滤条件:keyword
	selectedDeviceId:string = '';//过滤条件:设备ID
	selectedCarNumber:string = '';//过滤条件:车牌
	dateType:string = '1';	//过滤条件:时间类型
	selectedCompanyName = '';//过滤条件:公司名称
	selectedCompanyId = '';//过滤条件:公司ID
	isBsj:string = '';//过滤条件:是否博实结设备
//	checkStatus:string = '';//过滤条件:状态
	useTypeL2:string = '';//过滤条件:车辆分类二级
	useTypeL1:string = '';//过滤条件:车辆分类一级
	btnNum:string = 'all';
	activeSelected:string = ''; //row高亮
	selectedRow:any;		//选中的数据
	tabNumberList:any = [];	//tab数据数组
	flag:boolean = false;//记录弹层的显示和隐藏
	timeOut:any;
	isDelete = false;
	showMapflag:boolean = false;
	//判断是否有删除权限
 	initBtn(){
 		let btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_transport:orderManagenment')));
 		if(btnData){
 			for(let item of btnData){
 				if(item.sourceKey === "orderManagentment:delete"&&item.parentId){
 					this.isDelete = true;
 				}
 			}
 		}
 	}
	//table   分页
	load(){
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		const param = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				deviceId:this.selectedDeviceId,
				startTime:this.startTime,
				endTime:this.endTime,
				companyId:this.selectedCompanyId,
				carNumber:this.selectedCarNumber,
				dateType:this.dateType,
				searchKey:this.searchKey.trim(),
				orderStatus:'',
				checkStatus:'',
				isBsj:this.isBsj,
				useTypeL2:this.useTypeL2,
			}
		};
		switch (this.btnNum){
			case 'all':
				param.parameters.orderStatus = '';		//全部
				break;
			case 'trans':
				param.parameters.orderStatus = '0';		//运输中
				break;
			case 'normal':
				param.parameters.checkStatus = '0';		//正常卸货
				param.parameters.orderStatus = '1';		//运输中
				break;
			case 'gpsError':
				param.parameters.checkStatus = '1';		//gps异常
				break;
			case 'deviceOffLine':
				param.parameters.checkStatus = '2';		//设备异常
				break;
			default:
				break;
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.loadSortData(reqdata);
		this.jsonApiService.http("gpsOrderController/findOrderList.html", reqdata).subscribe(data => {
			if(data&&data.exhibitDatas){
				for(let item of data.exhibitDatas){
					item.sendWeight = common.twoDecimal(item.sendWeight);
					item.loadTime = common.secondToDate(item.loadTime);
					item.unloadTime = common.secondToDate(item.unloadTime);
					item.transportTime = common.secondToDate(item.transportTime);
				}
				this.tableData = data.exhibitDatas;
				this.totalCounts = data.recordCount;
			}
		})
	}
	//是否博实结设备
	isBsjChange(val){
		if(val){
			this.isBsj = "1";
		}else{
			this.isBsj = "0";
		}
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//分页回调
	paginate(e){
		this.activeSelected = '';
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//删除
	delete_Row(row){
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("gpsOrderController/deleteOrder.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	//订单分类汇总
	loadSortData(reqdata){
		this.jsonApiService.http("gpsOrderController/countOrderByStatus.html", reqdata).subscribe(data => {
			if(data&&data.data){
				this.tabNumberList = data.data;
			}
		})
	}
	//弹出层
	cancelDeviceDetail(){
		$('#deviceDetailModal').hide();
	}
	//row 双击
	baiduMapTools: any;
	rowSelectEvent(row,id){
		if($('#deviceDetailModal').attr('style').indexOf('display: block;') < 0){ //如果设备弹窗打开就刷新数据
			$('#deviceDetailModal').show();
		}
		this.deviceId = row.deviceId;
		this.baiduMapTools = this.myMap;
		this.initOrderDeviceModal(id);
	}
	//获取订单详情
	initOrderDeviceModal(id){
		this.activeSelected = id;
		this.jsonApiService.http_obj("gpsOrderController/getOrderInfo.html", {id:id}).subscribe(data => {
			if(data.success){
				this.selectedRow = data.data;
				this.deviceId = this.selectedRow.deviceId;
				this.carNumber = this.selectedRow.carNumber;
				this.selectedRow.sendWeight = (+this.selectedRow.sendWeight).toFixed(2);
				this.echartStartDate =  common.getTimeMmss(new Date(common.mmsstoTimestamp(this.selectedRow.emptyLoadTime) - 30*60*1000));//订单开始时间:往前推半个小时
				let temEndTime = this.selectedRow.unloadEndTime?this.selectedRow.unloadEndTime:this.selectedRow.lastDeviceTime;
				this.echartEndDate = common.getTimeMmss(new Date(common.mmsstoTimestamp(temEndTime) + 30*60*1000));//订单结束时间:往后推半个小时
				this.getDeviceBasicInfo();
				this.showCheart();//绘图
			}
		})
	}
	//查询
	table_search(){
		this.curPage = 1;
		this.activeSelected = '';
		this.load();
	}
	//数据分类按钮点击事件
	btnClick(type){
		this.btnNum = type;
		this.curPage = 1;
		this.flag = false;
		this.load();
	}
	//刷新
	refresh(){
		this.load();
	}
	
	//删除弹出层所选时间
	del_dateBtn(){
		$("#datetimepicker3").val('').change();
		$("#datetimepicker4").val('').change();
		$("#datetimepicker4").datetimepicker("setStartDate", null);
		$("#datetimepicker3").datetimepicker("setEndDate", null);
	}
	//订单详情  重新审核
	reserveOrder(){
		this.jsonApiService.confirm_message('您确定重新审核吗？').then(()=>{
			let reqdata = 'id=' + this.selectedRow.id;
			this.jsonApiService.http("gpsOrderController/reviewOrder.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.initOrderDeviceModal(this.activeSelected)
					this.load();
				}
			})
		});
	}
	//订单详情   查询按钮
	orderDetailSearch(){
		this.showCheart();
	}

	/**
	 *  地图显示&隐藏
	 */
	vIcon:string = '1';
	isShowMap:boolean = true;
	IsShowMap(){
		if(this.vIcon == '1'){
			$('#baiduMap').width('1156');
			$('#chart').css('left','478px');
			this.vIcon = '0';
			$(window).trigger('resize');
			this.isShowMap = false;
		}else{
			$('#baiduMap').width('678');
			$('#chart').css('left','0');
			this.vIcon = '1';
			$(window).trigger('resize');
			this.isShowMap = true;
		}
	}
	/**
	 * 围栏处理,在地图上显示围栏
	 */
	showRail(){
		const startIcon = "assets/img/rail/start.png";//起始点icon
		const endIcon = "assets/img/rail/end.png";//终点icon
		let railStyle = {
			strokeColor:'blue',
			fillColor:'red',
			strokeWeight:1,
			strokeOpacity:0.2,
			fillOpacity:0.2
		}//围栏圆样式
		let startPointToMap = toMapPoint({lng:this.selectedRow.consignorLng,lat:this.selectedRow.consignorLat});//大地转百度坐标系
		let startPoint = new BMap.Point(startPointToMap.lng, startPointToMap.lat);
//		let startPoint = new BMap.Point(this.selectedRow.consignorLng, this.selectedRow.consignorLat);
		var pStart = new BMap.Marker(startPoint, {
			icon: new BMap.Icon(startIcon, new BMap.Size(48, 56)),
			offset: new BMap.Size(15, 11),
			imageOffset: new BMap.Size(0, 0),
			imageSize: new BMap.Size(48, 56)
		});
		pStart.setZIndex(10);
		let startCircle = new BMap.Circle(startPoint,2000,railStyle); //创建圆
		this.myMap.addOverlay(pStart);//起始点
		this.myMap.addOverlay(startCircle);//起点圆
		this.getInOutTimeArr(0,startCircle);
		
		let endPointToMap = toMapPoint({lng:this.selectedRow.receivingLng,lat:this.selectedRow.receivingLat});//大地转百度坐标系
		let endPoint = new BMap.Point(endPointToMap.lng, endPointToMap.lat);
//		let endPoint = new BMap.Point(this.selectedRow.receivingLng, this.selectedRow.receivingLat);
		var pEnd = new BMap.Marker(endPoint, {
			icon: new BMap.Icon(endIcon, new BMap.Size(48, 56)),
			offset: new BMap.Size(15, 11),
			imageOffset: new BMap.Size(0, 0),
			imageSize: new BMap.Size(48, 56)
		});
		let endCircle = new BMap.Circle(endPoint,5000,railStyle); //创建圆
		this.myMap.addOverlay(pEnd);//终点
		this.myMap.addOverlay(endCircle);//终点圆
		this.getInOutTimeArr(0,endCircle);
	}
	//判断是否进入围栏
	getInOutTimeArr(order,chartAreaPly) {
		var isOut = false; //判断是否再进入边界后又再次出去
		var len = this.allData.length;
		for(var i = order; i < len; i++) {
			let pointToMapIn = toMapPoint({lng:this.allData[i].x,lat:this.allData[i].y});//大地转百度坐标系
			var comparePoint = new BMap.Point(pointToMapIn.lng, pointToMapIn.lat);
			var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, chartAreaPly);
			if(result) { //在内部，把该点显示在地图上  
				this.inTimeArr.push(this.allData[i].uploadDate);
				for(var j = i; j < len; j++) {
					let pointToMapOut = toMapPoint({lng:this.allData[j].x,lat:this.allData[j].y});//大地转百度坐标系
					var comparePoint = new BMap.Point(pointToMapOut.lng, pointToMapOut.lat);
					var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, chartAreaPly);
					if(!result) { //在内部，把该点显示在地图上  
						isOut = true; //判断是否再进入边界后又再次出去
						this.outTimeArr.push(this.allData[j].uploadDate);
						if(j < len) {
							this.getInOutTimeArr(j,chartAreaPly);
						}
						break;
					}
				}
				if(!isOut) {
					this.outTimeArr.push(this.allData[len - 1].uploadDate);
				}
				break;
			}
		}
	}

	/*
	 *  数据导出
	 */
	exportReport(){
		const param = {
			'deviceId':this.selectedDeviceId,
			'startTime':this.startTime,
			'endTime':this.endTime,
			'companyId':this.selectedCompanyId,
			'carNumber':this.selectedCarNumber,
			'dateType':this.dateType,
			'searchKey':this.searchKey.trim(),
			'orderStatus':'',
			'checkStatus':'',
			'useTypeL2':this.useTypeL2,
			'isBsj':this.isBsj,
		};
		switch (this.btnNum){
			case 'all':
				param.orderStatus = '';		//全部
				break;
			case 'trans':
				param.orderStatus = '0';		//运输中
				break;
			case 'normal':
				param.checkStatus = '0';		//正常卸货
				param.orderStatus = '1';		
				break;
			case 'gpsError':
				param.checkStatus = '1';		//gps异常
				break;
			case 'deviceOffLine':
				param.checkStatus = '2';		//设备异常
				break;
			default:
				break;
		}
		let timeCheck = common.correctTime(param, ['dateType'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(param, 'param', config.BaseURL + 'gpsOrderController/exportOrderDataRecordFile.html')
	}
	

	processInfo:string = '加载中...';
	inTimeArr:any = [];//地图进出围栏边界值
	outTimeArr:any = [];//地图进出围栏边界值
	myMap: any;
	linetoMap = true; //是否选择地图联动的条件
	carSpeed = true; //是否查看速度的条件
	showModify = true; //显示修正数据
	showApi = true;//api修正系数
	recordTime = '';
	filterTime = '';
	filterTimeDefault: number;
	companyId = '';
	carNumber = '';
	carList = [];
	companyList = [];
	deviceId = ''; //设备ID
	myChart: any;
	allData = []; //echart图后台请求回来的数据
	passageData = []; //所有chart图折线的数组
	linetoMapData = []; //地图联动画轨迹数据
	carSpeedArr = []; //速度折线的数据
	moveCanvasLayer: any; //轨迹移动添加点图层
	carMoveCanvasLayer: any; //移动折线对应地图添加点的图层,
	abnormalInfo; //地图上的异常警报窗口
	versionMessage = {
		name: '',
		versionString: '',
		runStatus: '',
		carUploadDate: '',
		gpsUploadDate: '',
		isShowGPS: false,
	}; //版本信息
	hideOrshowline = [];
	private isMoveFlag: boolean = true; //防抖节流，控制mousemove触发频率

	//速度y轴线
	yAxiSpeed: any = {
		show: true,
		name: '速度 KM/H',
		splitLine: {     
			show: false    
		},
		type: 'value',
		min: undefined,
		max: undefined,
		axisLine: {
			lineStyle: {
				color: '#5793f3'
			}
		},
		axisLabel: {
			formatter: '{value}'
		}
	}

	//	指定图表的配置项和数据
	echartOption:any = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross', //十字星
			},
			formatter: function(params) {
				if(this.linetoMap && this.isShowMap) {
					var paramIndex = params[0].dataIndex;
					var pointObj = this.linetoMapData[paramIndex];
					if(!pointObj || pointObj.x == '' || pointObj.x == '0') {
						return;
					}
					this.lineMoveCarPoint(pointObj)
				}
			}.bind(this)
		},
		grid: {
			left: '54px',
			right: '12px',
			top: '72px'
		},
		toolbox: {
			feature: {
				dataView: {
					show: false,
					readOnly: false
				},
				restore: {
					show: false
				},
				saveAsImage: {
					show: false
				}
			}
		},
		legend: {
			selected: {},
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: []
		},
		yAxis: [this.yAxiSpeed],

		dataZoom: [{
			realtime: true,
		}, {
			type: 'inside',
			realtime: true,
		}],
		series: [{
			name: '速度',
			type: 'line',
			data: []
		}]

	};
	legendSleced: any = {};

	//公司选中回调
	companySelected(val) {
		this.selectedDeviceId = val.deviceId;
		this.selectedCarNumber = val.carNumber;
		this.selectedCompanyId = val.companyId;
		this.selectedCompanyName = val.companyName;
		this.useTypeL2 = val.useTypeL2;
		this.useTypeL1 = val.useTypeL1;
	}
	//获取传感器参数
	getVersionMessage() {
		if(!this.deviceId) return;
		this.versionMessage = {
			name: '',
			versionString: '',
			runStatus: '',
			carUploadDate: '',
			gpsUploadDate: '',
			isShowGPS: false,
		}
		let reqdata = 'deviceId=' + this.deviceId;
		this.hideOrshowline = [];
		this.jsonApiService.http("system/getRealTimeData.html", reqdata).subscribe(result => {
			if(!result.success) return;
			this.versionMessage.name = result.data.version;
			this.versionMessage.runStatus = result.data.runStatus;
			this.versionMessage.carUploadDate = result.data.carUploadDate;
			this.versionMessage.gpsUploadDate = result.data.gpsUploadDate;
			let abs = Math.abs(common.mmsstoTimestamp(this.versionMessage.carUploadDate) - common.mmsstoTimestamp(this.versionMessage.gpsUploadDate));
			abs >= 30 * 60 * 1000 ? this.versionMessage.isShowGPS = true : this.versionMessage.isShowGPS = false;
			let coefArr = [];
			if(!result.data.coef) return
			for(let i = 0; i < result.data.coef.length; i++) {
				let item = result.data.coef[i];
				if(item) {
					let vname = '通道' + (i + 1);
					coefArr.push(vname + ':' + item);
					this.hideOrshowline.push(vname)
				}
			}
			let resultString = '';
			for(let _i = 0; _i < coefArr.length; _i++) {
				if(_i < coefArr.length - 1) {
					resultString += coefArr[_i] + ',';
				} else {
					resultString += coefArr[_i]
				}
			}
			this.versionMessage.versionString = resultString;
		})
	}
	ngOnInit() {
		this.initBtn();
		const self = this;
		this.tableMove();
		this.initDate().then(() => {
			this.load();
		});
		this.myChart = echarts.init(document.getElementById('chart'));
		this.initChart();
		window.onresize = function(){
			setTimeout(()=>{
				self.myChart.resize()
			},120)
		}
		let map = new BMap.Map('baiduMap', {
			enableMapClick: false
		}); //创建地图实例
		let point = new BMap.Point(116.404, 39.915); //创建点坐标
		map.centerAndZoom(point, 15); //初始化地图，设置中心点坐标和地图级别
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		map.disableDoubleClickZoom(); //禁用双击放大
		this.myMap = map;
	}
	ngOnDestroy() {
		window.onresize = null;
		document.onclick = null;
	}
	echartStartDate:string = '';
	echartEndDate:string = '';
	//初始化时间
	initDate() {
		let that = this;
		return new Promise(function(resolve, error) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#datetimepicker1").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function(e) {
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.startTime = time
						$("#datetimepicker2").datetimepicker("setStartDate", time);
						$("#datetimepicker1").change();
					});
					$("#datetimepicker2").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function(e) {
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.endTime = time;
						$("#datetimepicker1").datetimepicker("setEndDate", time);
						$("#datetimepicker2").change();
					});
					var date = new Date();
					let time1 = common.getTimeMmss(date);
					$("#datetimepicker2").val(time1); //当前时间
					that.endTime = time1;
					date.setDate(date.getDate() - 7); //设置前一周
					let time2 = common.getTimeMmss(date);
					$("#datetimepicker1").val(time2);
					that.startTime = time2;


					$("#datetimepicker3").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true
					}).on("changeDate", function(e){
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.echartStartDate = time;
						$("#datetimepicker4").datetimepicker("setStartDate", time);
					});
					$("#datetimepicker4").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true
					}).on("changeDate", function(e){
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.echartEndDate = time;
						$("#datetimepicker3").datetimepicker("setEndDate", time);
					});
					resolve();
				})
			})
		});
	}
	//初始化echart图
	initChart() {
		this.allData = []; //echart图后台请求回来的数据
		this.passageData = []; //所有chart图折线的数组
		this.linetoMapData = []; //地图联动画轨迹数据
		this.carSpeedArr = []; //速度折线的数据
		this.echartOption.xAxis.data = [];
		this.echartOption.series = [];
		this.myChart.clear();
		this.myChart.setOption(this.echartOption, true);
	}

	//	//初始化公司树数据

	//百度地图绘画路线,不带方向箭头,当前版本不用该函数
	drawTrack(map, param) {
		var pointArr = param;
		map.clearOverlays();

		var linkPoint = [];
		var linkPoint = []; //拼接线的折点

		for(var i = 0; i < pointArr.length; i++) {
			//    转换成百度坐标
			var mapPoint = toMapPoint(pointArr[i]);
			if(mapPoint) {
				linkPoint.push(new BMap.Point(mapPoint.lng, mapPoint.lat));
			}
		}
		var polyline = new BMap.Polyline(linkPoint, {
			strokeColor: "#4169e1",
			strokeWeight: 6,
			strokeOpacity: 0.9
		}); //创建折线
		map.addOverlay(polyline);
		var starPoint = new BMap.Point(pointArr[0].lng, pointArr[0].lat);
		var endPoint = new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat);
		var opts = {
			position: starPoint, // 指定起点所在的地理位置
			offset: new BMap.Size(0, 0) //文本偏移量
		};
		var endOpts = {
			position: endPoint, // 指定终点点所在的地理位置
			offset: new BMap.Size(0, 0) //文本偏移量
		};
		var label = new BMap.Label('起点', opts); // 创建文本内容
		var endLabel = new BMap.Label('终点', endOpts); // 创建文本内容
		label.setStyle({
			color: "red",
			fontSize: "12px",
			height: "20px",
			padding: "0px 30px 0 2px",
			margin: 0,
			lineHeight: "20px",
			fontFamily: "微软雅黑"
		});
		endLabel.setStyle({
			color: "red",
			fontSize: "12px",
			height: "20px",
			padding: "0px 30px 0 2px",
			margin: 0,
			lineHeight: "20px",
			fontFamily: "微软雅黑"
		});
		map.addOverlay(label);
		map.addOverlay(endLabel);
		setTimeout(function() {
			map.centerAndZoom(new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat), 10);
		}, 10);
	}

	//定义转换时间戳函数
	changeTime(str) {
		let str1 = str.replace(/-/g, "/");
		let timestamp = new Date(str1).getTime();
		return timestamp;
	}
	mapClick:boolean = true;	//地图点击防抖节流
	//生成echart折线图
	showCheart() {
		this.myMap.clearOverlays();
		function nullUpdate() {}
		this.carMoveCanvasLayer = new CanvasLayer({
			map: this.myMap,
			update: nullUpdate,
			zIndex: 10
		});
		this.moveCanvasLayer = new CanvasLayer({
			map: this.myMap,
			update: nullUpdate,
			zIndex: 10
		});
		this.myMap.addOverlay(this.carMoveCanvasLayer);
		this.myMap.addOverlay(this.moveCanvasLayer);
		this.myChart = null;
		this.myChart = echarts.init(document.getElementById('chart'));
		this.myChart.clear();
		this.myChart.setOption(this.echartOption, true);
		this.askforData();
		let that = this;
		this.myChart.off("click");
		this.myChart.on('click', function(params) {
			var pointObj = that.allData[params.dataIndex];
			if(pointObj == undefined) {
				return;
			}
			var geturl = config.BaseURL;
			pointObj.companyName = that.selectedCompanyName;
			if(that.mapClick){
				common.createInfoBox(that.myMap, pointObj, geturl);
				that.mapClick = false;
				setTimeout(()=>{
					that.mapClick = true;
				},300);
			}
		}.bind(this))
	}
	//后台获取数据
	askforData() {
		this.processInfo = '加载中...';
		this.inTimeArr = [];
		this.outTimeArr = [];
		let startTime = this.echartStartDate;
		let endTime = this.echartEndDate;
		this.initChart();
		layer.load();
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + startTime + '&endTime=' + endTime + '&showModify='+this.showModify+'&showApi='+this.showApi;
		this.jsonApiService.http2("gpsOrderController/getCarDataList.html", reqdata).subscribe(data => {
			layer.closeAll('loading');
			this.getVersionMessage();
			this.allData = data.data;
			if(this.allData.length < 2) {
				this.jsonApiService.message('没有数据');
				this.processInfo = '没有数据';
				return;
			}
			this.processInfo = '';
//			this.showRail();//围栏显示
			this.linetoMapData = []; //地图联动轨迹画线数据
			this.carSpeedArr = []; //画速度折线数据
			let timeValue = [];
			let len = this.allData.length;
			var lostWeightMark = []; //计算丢失重量的时长
			let nullGpsArr = []; //经纬度为空或者0.0的画折线数据
			var nullMarkerData = []; //计算经纬度丢失的时长
			let isLostGps = false; //是否有丢失经纬度
			var isHavePoint = 0; //控制判断经纬度丢失起始结束位置计算时间条件
			/**
			 * 计算采样周期,用于判断重量丢失的阈值
			 * 取10组历史数据,取中位数作为数据采样的频率
			 */
			let temFilterArr: any = [];
			this.filterTimeDefault = 0;
			if(len > 10) {
				for(let i = 0; i < 10; i++) {
					let time1 = this.changeTime(this.allData[i].uploadDate);
					let time2 = this.changeTime(this.allData[i + 1].uploadDate);
					let diffTime = (time2 - time1) / 1000;
					temFilterArr.push(diffTime)
				}
				temFilterArr.sort(function(a, b) {
					return a - b;
				})
				this.filterTimeDefault = Number(temFilterArr[6]) * 1.5;
			} else {
				this.filterTimeDefault = (this.changeTime(this.allData[1].uploadDate) - this.changeTime(this.allData[0].uploadDate)) / 1000 * 1.5;
			}
			if(this.filterTime) {
				this.filterTimeDefault = Number(this.filterTime) > this.filterTimeDefault ? Number(this.filterTime) : this.filterTimeDefault;
			}
			this.filterTimeDefault = this.filterTimeDefault > 150 ? this.filterTimeDefault : 150;
			for(var i = 0; i < len; i++) {
				timeValue[i] = this.allData[i].uploadDate; //x时间轴数据
				let _speed = parseFloat(this.allData[i].speed); //速度
				if(_speed > -1) {
					this.carSpeedArr[i] = parseFloat(this.allData[i].speed);
				} else {
					this.carSpeedArr[i] = 0;
				}
				nullGpsArr[i] = '--';
				//计算经纬度等于0.0或者丢失的时候是时长start
				if(!this.allData[i] || !this.allData[i].x || this.allData[i].x == '0.0') {
					if(isHavePoint < 1) {
						isHavePoint = i;
					}
				} else {
					if(isHavePoint > 0) {
						var lostTime = (this.changeTime(this.allData[i].uploadDate) - this.changeTime(this.allData[isHavePoint].uploadDate)) / 1000;
						if(lostTime > this.filterTimeDefault) {
							var point = {
								value: this.convertTime(lostTime),
								xAxis: isHavePoint,
								yAxis: this.allData[isHavePoint].weight,
								lostime: lostTime,
							};
							nullMarkerData.push(point);
						}
						isHavePoint = 0
					}
				}
				//计算end
				if(i < len - 2) {
					//获取丢失的数据
					let lostStartime = this.changeTime(this.allData[i].uploadDate);
					let lostEndtime = this.changeTime(this.allData[i + 1].uploadDate);
					let lostime = (lostEndtime - lostStartime) / 1000;
					if(lostime > this.filterTimeDefault) { //重量时间段丢失
						var point = {
							value: this.convertTime(lostime),
							xAxis: i,
							yAxis: this.allData[i].weight,
							lostime: lostime,
						};
						lostWeightMark.push(point);
					}
					if(!this.allData[i].x || this.allData[i].x == '0.0') {
						//经纬度坐标丢失
						if(i > 0) {
							isLostGps = true;
							nullGpsArr[i] = this.allData[i].weight;
						}
					}
				}
				var mapPoint = toMapPoint(this.allData[i]);
				if(mapPoint && mapPoint.lng && mapPoint.lat && mapPoint.lng !== '0.0' && mapPoint.lat !== '0.0' && mapPoint.lat != '0' && mapPoint.lng != '0') {
					this.linetoMapData[i] = this.allData[i];
				}
			}
			//查询连续性为空的经纬度数据结束空的位置
			this.passageData = [];
			//获取异常信息数据
			var self = this;
			//时间轴
			this.echartOption.xAxis.data = timeValue;
			if(this.carSpeed) {
				this.yAxiSpeed.min = 0;
				this.yAxiSpeed.max = 120;
				this.showCarSpeed();
			}
			this.yAxiSpeed.show = this.carSpeed;
			this.echartOption.series = this.passageData;
			this.echartOption.legend.selected = this.legendSleced;
			this.jsonApiService.http2("realtime/getRealTimeDataForBase.html", 'deviceId=' + this.deviceId).subscribe(result => {
				if(result.data.unit == '2') {
					this.echartOption.series[0].name = '重量（千克）';
				}
				
				this.myChart.setOption(this.echartOption, true);
				this.showMapTrack();
			})
		})
	}

	//绘画车辆速度折线
	showCarSpeed() {
		let obj = {
			name: '车辆速度',
			type: 'line',
			yAxisIndex: 0,
			itemStyle: {
				normal: {
					color: '#5793f3',
					lineStyle: {
						width: 1, //折线宽度
						opacity: 0.5,
					}
				}
			},
			data: this.carSpeedArr,
			areaStyle: {
				color: 'rgba(83, 146, 230,0.5)'
			}
		};
		this.passageData.push(obj);
	}
	//地图联动绘画轨迹路线.
	showMapTrack() {
		let pointArr = this.linetoMapData;
		let map = this.myMap;
		//绘制路线
		var geturl = config.BaseURL;
		let lineStyle = {
			star: true,
			end: false,
			color: true,
			infoUrl: geturl
		};
		drawTrackLine(pointArr, map, lineStyle);
		setTimeout(function() {
			for(let item of pointArr){
				if(item){
					map.centerAndZoom(new BMap.Point(item.lng, item.lat), 12);
				}
				break;
			}
		}, 10);
	}
	//折线移动,地图轨迹添加坐标位置点函数
	lineMoveCarPoint(data) {
		if(data.lat > 0) {
			var mp = this.myMap;
			var update = function update() {
				var ctx = this.canvas.getContext("2d");
				if(!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
				var point = new BMap.Point(data.lng, data.lat);
				var pixel = mp.pointToPixel(point);
				ctx.beginPath();
				ctx.strokeStyle = '#d0d4d7';
				ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = 'rgba(35, 152, 255, 0.14)';
				ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.strokeStyle = '#c2c2c4';
				ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = '#fff';
				ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle = '#1496ff';
				ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
				ctx.fill();
			};
			if(typeof this.carMoveCanvasLayer != 'undefined') {
				this.carMoveCanvasLayer.options.update = update;
				this.carMoveCanvasLayer._draw();
				return;
			}
			this.carMoveCanvasLayer = new CanvasLayer({
				map: this.myMap,
				update: update,
				zIndex: 10
			});

		}
	}
	//车辆速度选中画折线
	carSpeedChange() {
		if(this.carSpeedArr.length >= 1) {
			if(this.carSpeed) {
				this.yAxiSpeed.min = 0;
				this.yAxiSpeed.max = 120;
				this.showCarSpeed();
			} else {
				this.yAxiSpeed.min = undefined;
				this.yAxiSpeed.max = undefined;
				let len = this.passageData.length;
				for(var i = 0; i < len; i++) {
					if(this.passageData[i].name === '车辆速度') {
						this.passageData.splice(i, 1);
						break;
					}
				}
			}
			this.yAxiSpeed.show = this.carSpeed;
			this.echartOption.series = this.passageData;
			this.myChart.setOption(this.echartOption, true);
		}
	}

	//转换时间格式
	convertTime(timeInt) {
		var d, h, m, s;
		if(timeInt >= 0) {
			d = Math.floor(timeInt / 60 / 60 / 24);
			h = Math.floor(timeInt / 60 / 60 % 24);
			m = Math.floor(timeInt / 60 % 60);
			s = Math.floor(timeInt % 60);
		}
		if(d < 1) {
			if(h < 1) {
				// 	 return m+'分'+s+'秒';
				return '约' + m + '分';
			} else {
				return h + '小时' + m + '分';
			}
		} else {
			return d + '天' + h + '小时' + m + '分';
		}
	}

	
	//根据编码映射对应车辆类型名称
	getUseTypeNameL2(key) {
		if(key) {
			return this.TcarDeatailUseList[key];
		} else {
			return '';
		}
	}

	TcarUseList = carTypeListObj.carUseList
	TcarDeatailUseList = carTypeListObj.carDeatailUseList
	/**
	 * 设备详细(设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	tableMove() {
		$('body').undelegate('#headDrag','mousedown',function(){});
		$('body').delegate('#headDrag', 'mousedown', function(e) {
			$(this).css("cursor", "move");
			var offset = $('#deviceDetailModal').position();
			var x = e.pageX - offset.left;
			var y = e.pageY - offset.top;
			$(document).bind("mousemove", function(ev) {
				$("#deviceDetailModal").stop();
				var _x = ev.pageX - x;
				var _y = ev.pageY - y;
				if(_y < 0){ //避开头部横条
					return;
				}
				$("#deviceDetailModal").animate({
					left: _x + "px",
					top: _y + "px"
				}, 2);
			});
		});
		$(document).mouseup(function() {
			$("#deviceDetailModal").css("cursor", "default");
			$(this).unbind("mousemove");
		});
	}
	/**
	 * 获取设备信息 (设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	deviceBaseInfo: any = {
		companyName: '',
		carNumber: '',
		deviceId: '',
		hwVersion: '',
		useTypeL1: '',
		useTypeL2: '',
		userTypeName: '',
		sensorType: '',
		productNo: '',
		iccid: '',
		driverName: '',
		phone: '',
		inputDate: '',
		installTime:'',
		userNameForCreate: '',
		sensorChannel: [],
		coef: [],
		coefT: [],
		version: ''
	};

	initDeviceBaseInfo() {
		this.deviceBaseInfo = {
			companyName: '',
			carNumber: '',
			deviceId: '',
			hwVersion: '',
			useTypeL1: '',
			useTypeL2: '',
			userTypeName: '',
			sensorType: '',
			productNo: '',
			iccid: '',
			driverName: '',
			phone: '',
			inputDate: '',
			installTime:'',
			userNameForCreate: '',
			sensorChannel: [],
			coef: [],
			coefT: [],
			version: ''
		};
	}
	//设备基本信息
	getDeviceBasicInfo(){
		this.jsonApiService.http_obj("system/getDeviceBaseInfoByDeviceId.html", {
			deviceId: this.deviceId
		}).subscribe(data => {
			if(data.success && data.data) {
				for(let item in this.deviceBaseInfo) {
					if(item === 'coef' || item === 'coefT' || item === 'sensorChannel') {
						this.deviceBaseInfo[item] = data.data[item] || [];
					} else {
						this.deviceBaseInfo[item] = data.data[item] || '';
					}
				}
				this.deviceBaseInfo.userTypeName = this.getUseTypeNameL2(this.deviceBaseInfo.useTypeL2);
				if(this.deviceBaseInfo.sensorChannel&&this.deviceBaseInfo.sensorChannel.length > 0){
						let temArr:any = [];
						for(var j = 0; j < this.deviceBaseInfo.sensorChannel.length; j++){
							let obj = {
								value:this.deviceBaseInfo.sensorChannel[j],
								flag:false,
							}
							if(this.deviceBaseInfo.coef){
								if(this.deviceBaseInfo.coef[+this.deviceBaseInfo.sensorChannel[j]-1]){
									obj.flag = true;
								}
							}
							temArr.push(obj);
						}
						this.deviceBaseInfo.sensorChannel = temArr;
					}
				if(this.deviceBaseInfo.coef) {
					let coefArr = [];
					for(let i = 0; i < this.deviceBaseInfo.coef.length; i++) {
						let _item = this.deviceBaseInfo.coef[i];
						if(_item) {
							let obj: any = {
								value: _item,
								index: i + 1
							}
							coefArr.push(obj);
						}
					}
					this.deviceBaseInfo.coefT = coefArr;
				} else {
					this.deviceBaseInfo.coefT = [];
				}
				if(this.deviceBaseInfo.inputDate){
					this.deviceBaseInfo.installTime = common.secondToDate((common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceBaseInfo.inputDate))/1000)
				}
			}

		})
	}
}